<template>
  <div class="user-list-container">
    <el-card>
      <h2>用户列表</h2>
      <div>
        <el-select v-model="selectedRole" placeholder="请选择角色">
          <el-option v-for="(role, key) in roleMap" :key="key" :label="role" :value="role" />
        </el-select>
        <el-button type="primary" @click="handleGetUserList">查询</el-button>
      </div>

      <el-table
        :data="userList"
        border
        stripe
        v-loading="isLoading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="account" label="账号" width="180" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="address" label="地址" min-width="200" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            {{ getRoleText(scope.row.role) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { getAllUsers, getCustomers, getStaffs, getStations, getRepairmen } from '@/api/user'
import { ElMessage } from 'element-plus'
import { onMounted } from 'vue'
// 状态管理
const userList = ref([])
const isLoading = ref(false)
const selectedRole = ref(null) // 选择的角色
// 角色文本映射
const roleMap = {
  0: '客户',
  1: '客服',
  2: '站点',
  3: '维修员',
  4: '管理员',
}

// 获取用户列表
const fetchUserList = async () => {
  isLoading.value = true
  try {
    const res = await getAllUsers()
    if (res.code === 200) {
      userList.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {
    ElMessage.error('获取用户列表失败', err.message)
  } finally {
    isLoading.value = false
  }
}
const handleGetUserList = async () => {
  isLoading.value = true
  try {
    let res
    console.log(selectedRole.value)

    switch (selectedRole.value) {
      case '管理员':
        res = await getAllUsers()
        break
      case '客户':
        res = await getCustomers()
        break
      case '客服':
        res = await getStaffs()
        break
      case '站点':
        res = await getStations()
        break
      case '维修员':
        res = await getRepairmen()
        break
      default:
        res = await getAllUsers()
    }
    if (res.code === 200) {
      userList.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {
    ElMessage.error('获取用户列表失败', err)
  } finally {
    isLoading.value = false
  }
}
// 组件挂载时加载数据
onMounted(() => {
  fetchUserList()
})

// 角色文本转换函数
const getRoleText = (role) => roleMap[role] || '未知'
</script>

<style scoped>
.user-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
</style>
